package com.yjc.drygoods.product.service.impl;

import com.yjc.common.constant.AttrEnum;
import com.yjc.common.utils.PageUtils;
import com.yjc.drygoods.product.dao.AttrAttrgroupRelationDao;
import com.yjc.drygoods.product.dao.AttrDao;
import com.yjc.drygoods.product.dao.AttrGroupDao;
import com.yjc.drygoods.product.dao.CategoryDao;
import com.yjc.drygoods.product.entity.AttrAttrgroupRelationEntity;
import com.yjc.drygoods.product.entity.AttrEntity;
import com.yjc.drygoods.product.entity.AttrGroupEntity;
import com.yjc.drygoods.product.entity.CategoryEntity;
import com.yjc.drygoods.product.service.AttrService;
import com.yjc.drygoods.product.service.CategoryService;
import com.yjc.drygoods.product.vo.AttrRespVo;
import com.yjc.drygoods.product.vo.AttrVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
@Slf4j
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //保存完后会将数据库的id主键返回并注入进attrEntity
        this.save(attrEntity);

        log.info("AttrType:{},AttrEnum.ATTR_TYPE_BASE.getCode():{}", attr.getAttrType(), AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attr.getAttrType() == AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Transactional
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
        queryWrapper.eq
                ("attr_type", "base".equalsIgnoreCase(type) ? AttrEnum.ATTR_TYPE_BASE.getCode() : AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((i) -> i.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> collect = records.stream().map((item) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(item, attrRespVo);
            CategoryEntity categoryEntity = categoryDao.selectOne
                    (new QueryWrapper<CategoryEntity>().eq("cat_id", item.getCatelogId()));
            AttrGroupEntity attrGroupEntity = null;
            if (item.getAttrType() == AttrEnum.ATTR_TYPE_BASE.getCode()) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne
                        (new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
                if (attrAttrgroupRelationEntity != null) {
                    attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                }
            }
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            if (attrGroupEntity != null) {
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(collect);
        return pageUtils;

    }

//    @Cacheable(value = {"attr"}, key = "'getAttrInfo:'+#root.args[0]")
    //后台也要调用这个方法，所以暂时不能使用缓存
    @Transactional
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity byId = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(byId, attrRespVo);

        if (byId.getAttrType() == AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationDao.selectOne
                    (new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", byId.getAttrId()));
            if (attrAttrgroupRelation != null) {
                Long attrGroupId = attrAttrgroupRelation.getAttrGroupId();
                attrRespVo.setAttrGroupId(attrGroupId);
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                if (attrGroupEntity != null) {
                    String attrGroupName = attrGroupEntity.getAttrGroupName();
                    attrRespVo.setGroupName(attrGroupName);
                }
            }
        }

        CategoryEntity categoryEntity = categoryDao.selectById(byId.getCatelogId());
        if (categoryEntity != null) {
            String catelogName = categoryEntity.getName();
            attrRespVo.setCatelogName(catelogName);
        }
        Long[] catelogPath = categoryService.findCatelogPath(byId.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);


        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);


        if (attr.getAttrType() == AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelation.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelation.setAttrId(attr.getAttrId());

            Integer count = attrAttrgroupRelationDao.selectCount
                    (new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
                attrAttrgroupRelationDao.update(attrAttrgroupRelation, wrapper.eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelation);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelation =
                attrAttrgroupRelationDao.selectList(wrapper.eq("attr_group_id", attrgroupId));
        List<AttrEntity> collect = attrAttrgroupRelation.stream().map(item -> {
            AttrEntity byId = this.getById(item.getAttrId());
            return byId;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public PageUtils getNoattrRelation(Map<String, Object> params, Long attrgroupId) {
        String key = (String) params.get("key");
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        if (attrGroupEntity == null) {
            log.info("attrGroupEntity为空-->AttrServiceImpl-->getNoattrRelation");
            return null;
        }
        Long catelogId = attrGroupEntity.getCatelogId();
        QueryWrapper<AttrGroupEntity> wrapper1 = new QueryWrapper<>();
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(wrapper1.eq("catelog_id", catelogId));
        //获取到当前分类下所有分组id
        List<Long> attrGroupIds = attrGroupEntities.stream().map(attrGroupEntitiy -> {
            return attrGroupEntitiy.getAttrGroupId();
        }).collect(Collectors.toList());
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper2 = new QueryWrapper<>();
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelations
                = attrAttrgroupRelationDao.selectList(wrapper2.in("attr_group_id", attrGroupIds));
        //获取到所有已被关联属性
        List<Long> attrIds = attrAttrgroupRelations.stream().map(i -> {
            return i.getAttrId();
        }).collect(Collectors.toList());
        //从当前分类中的属性中移除这些已关联属性
        QueryWrapper<AttrEntity> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("catelog_id", catelogId).eq("attr_type", AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0) {
            wrapper3.notIn("attr_id", attrIds);
        }
        if (!StringUtils.isEmpty(key)) {
            wrapper3.and(i -> i.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper3
        );
        return new PageUtils(page);

    }

    @Override
    public List<Long> getAllowSearchAttr(List<Long> attrList) {

        return this.baseMapper.selectAllowSearchAttr(attrList);
    }

}